package com.ruoyi.dj.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.props.AllPathProperties;
import com.ruoyi.common.constant.TableConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ProcessStopException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExecUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SseEmitterUtils;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.common.utils.biz.ResultSaveModule;
import com.ruoyi.dj.mapper.TerrMagnetismMapper;
import com.ruoyi.dj.service.TerrMagnetismService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class TerrMagnetismServiceImpl implements TerrMagnetismService {

    @Autowired
    private AllPathProperties allPath;
    @Resource
    private TerrMagnetismMapper terrMagnetismMapper;
    @Override
    public String getTatestTime(String index) {
        String tableName = TableConstants.getTableName(index);
        //获取数据库数据最新日期 并+1天
        String tatestTime = terrMagnetismMapper.getTatestTime(tableName);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtils.convertString2Date("yyyy-MM-dd HH:mm:ss",tatestTime));
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date date = calendar.getTime();
        return DateUtils.convertDate2String("yyyy-MM-dd HH:mm:ss", date);
    }

    /**
     * 根据指数、预报方法、预报时间获取结果数据
     */
    @Override
    public AjaxResult getData(String index, String method, String time, String sseId) throws ProcessStopException {
        String tatestTime = this.getTatestTime(index);
        boolean after = DateUtil.parseDateTime(time).after(DateUtil.parseDateTime(tatestTime));
        if (after){
            return AjaxResult.error("对于"+index+"的预报起始时间不能超过"+tatestTime);
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        sseId+=loginUser.getUsername();
        List<String> command = new ArrayList<>();
        command.add("python");
        command.add("-u");
        String pythonPath = allPath.getRootPath().getBase()
                + allPath.getRootPath().getPathCode()
                + allPath.getModuleDir().getModelCal().get("dir")
                + allPath.getModuleDir().getModelCal().get("arima");
        command.add(pythonPath);
        command.add(index);
        command.add(time.replaceAll(" ","-"));
        command.add(method);
//        //调用python程序
        System.out.println(command.get(0)+" "+command.get(1)+" "+command.get(2)+" "+command.get(3)+" "+command.get(4)+" "+command.get(5));
        String results = ExecUtil.execPython(command, sseId);
        System.out.println(results);
//        String results = "{'DATETIME': ['2021-11-08', '2021-11-09', '2021-11-10', '2021-11-11', '2021-11-12', '2021-11-13', '2021-11-14', '2021-11-15', '2021-11-16', '2021-11-17', '2021-11-18', '2021-11-19', '2021-11-20', '2021-11-21', '2021-11-22', '2021-11-23', '2021-11-24', '2021-11-25', '2021-11-26', '2021-11-27', '2021-11-28', '2021-11-29', '2021-11-30', '2021-12-01', '2021-12-02', '2021-12-03', '2021-12-04', '2021-12-05', '2021-12-06', '2021-12-07', '2021-12-08', '2021-12-09', '2021-12-10', '2021-12-11', '2021-12-12', '2021-12-13', '2021-12-14', '2021-12-15', '2021-12-16', '2021-12-17', '2021-12-18', '2021-12-19', '2021-12-20', '2021-12-21', '2021-12-22', '2021-12-23', '2021-12-24', '2021-12-25', '2021-12-26', '2021-12-27', '2021-12-28', '2021-12-29', '2021-12-30', '2021-12-31', '2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06', '2022-01-07', '2022-01-08', '2022-01-09', '2022-01-10', '2022-01-11', '2022-01-12', '2022-01-13', '2022-01-14', '2022-01-15', '2022-01-16', '2022-01-17', '2022-01-18', '2022-01-19', '2022-01-20', '2022-01-21', '2022-01-22', '2022-01-23', '2022-01-24', '2022-01-25', '2022-01-26', '2022-01-27', '2022-01-28', '2022-01-29', '2022-01-30', '2022-01-31', '2022-02-01', '2022-02-02', '2022-02-03', '2022-02-04', '2022-02-05', '2022-02-06', '2022-02-07', '2022-02-08', '2022-02-09', '2022-02-10', '2022-02-11', '2022-02-12', '2022-02-13', '2022-02-14', '2022-02-15', '2022-02-16', '2022-02-17', '2022-02-18', '2022-02-19', '2022-02-20', '2022-02-21', '2022-02-22', '2022-02-23'], 'F107_obs': [89.0, 89.0, 89.0, 82.0, 82.0, 82.0, 79.0, 79.0, 78.0, 78.0, 78.0, 78.0, 78.0, 78.0, 79.0, 79.0, 83.0, 84.0, 90.0, 90.0, 90.0, 90.0, 88.0, 84.0, 84.0, 84.0, 83.0, 80.0, 78.0, 77.0, 75.0, 74.0, 74.0, 74.0, 77.0, 78.0, 86.0, 99.0, 114.0, 114.0, 117.0, 117.0, 119.0, 126.0, 126.0, 126.0, 126.0, 122.0, 121.0, 120.0, 116.0, 108.0, 99.0, 98.0, 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null'], 'F107_pred': ['Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 'Null', 97.0, 96.0, 95.0, 95.0, 94.0, 94.0, 94.0, 94.0, 93.0, 93.0, 93.0, 93.0, 93.0, 93.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0]}";
        results = results.replaceAll("\'","\"").replaceAll("Null","null").replaceAll(index+"_obs","obs").replaceAll(index+"_pred","pred");
        if (results.contains("###")){
            System.out.println(results);
            results = results.split("###")[1];
        }
        String filePath = PathUtil.tmpModuleDir(BizModule.MODEL_CAL)+"/magRadiation/result_"+
                DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT) + ".txt";
        FileWriter.create(new File(filePath)).write(results);
        //进行Json字符串转换
        Map<String,Object> map = JSON.parseObject(results, Map.class);
        if (map.isEmpty()){
            return AjaxResult.success("获取数据元素为空");
        }
        Map<String,Object> resMap = new HashMap<>();

        //进行列表数据封装
        List<Map<String,Object>> list = new ArrayList<>();
        //获取时间列表
        List<String> timeList = (List<String>) map.get("DATETIME");
        //获取观测值列表
        List<Object> obsList = (List<Object>) map.get("obs");
        if (null == obsList) {
            obsList = (List<Object>) map.get("Kp_obs");
            map.put("obs",obsList);
        }
        //获取预报值列表
        List<Object> preds = (List<Object>) map.get("pred");
        if (preds == null) {
            preds = ((List<Object>) map.get("Kp_pred"));
            map.put("pred",preds);
        }
        //添加折线图信息
        resMap.put("lineChart",map);
        List<Object> predList = preds.stream()
                .map(obj -> {
                    if (obj instanceof Number) {
                        BigDecimal bd = new BigDecimal(obj.toString());
                        bd = bd.setScale(1, RoundingMode.HALF_UP);
                        return bd.doubleValue();
                    }
                    return obj;
                })
                .collect(Collectors.toList());
        map.put("pred", predList);
        for (int i = 0; i<timeList.size()-1; i++) {
            Map<String, Object> mp = new HashMap<>();
            mp.put("DATETIME",timeList.get(i));
            mp.put("obs",obsList.get(i));
            mp.put("pred",predList.get(i));
            list.add(mp);
        }
        //添加统计表信息
        resMap.put("tableData",list);

        resMap.put("resultData", JSONUtil.toJsonStr(Stream.of(filePath).collect(Collectors.toList())));
        resMap.put("module", ResultSaveModule.MODEL_CAL);
        resMap.put("submodule", ResultSaveModule.MODEL_CAL_MAG);

        SseEmitterUtils.remove(sseId);
        return AjaxResult.success("获取成功",resMap);
    }
    @Override
    public SseEmitter push(String id, String flag) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return SseEmitterUtils.connect(id+loginUser.getUsername(), flag);
    }
}
